
import heapq
import os
import urllib
from datetime import datetime, timedelta

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import models

class LandingPage(webapp.RequestHandler):
  def get(self):
    self.redirect('/daily_review')


class DailyReview(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    assert user

    freshness_cutoff = datetime.now() - timedelta(hours=15)
    query = models.CardEntry.all().filter('user', user).order('times_viewed')

    entries = []
    for e in query:
      if freshness_cutoff < e.last_viewed:
        continue
      entries.append(e)
      if len(entries) == 20:
        break

    template_args = {
      'entries' : entries,
      'reviewed_words' : ','.join(e.entry for e in entries),
    }
    path = os.path.join(os.path.dirname(__file__), 'daily_review.tpl')
    self.response.out.write(template.render(path, template_args))

  def post(self):
    reviewed_words = self.request.get('reviewed').split(',')
    for word in reviewed_words:
      entry = models.CardEntry.all().filter('entry', word).get()
      assert entry
      entry.times_viewed += 1
      entry.last_viewed = datetime.now()
      entry.put()
    self.redirect('/daily_review')


class EntryMode(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    assert user
    entries = models.CardEntry.all().filter('user', user).order('-date_added').fetch(5)

    template_args = {
      'entries' : entries,
      'lookup' : self.request.get('lookup')
    }
    path = os.path.join(os.path.dirname(__file__), 'entry_mode.tpl')
    self.response.out.write(template.render(path, template_args))

  def post(self):
    user = users.get_current_user()
    assert user

    entry_word = self.request.get('entry').strip()
    if not entry_word:
      raise Exception('Entry is empty')

    existing = models.CardEntry.all().filter('entry', entry_word).get()
    entry = models.CardEntry(
        entry=entry_word,
        definition=self.request.get('definition').strip(),
        user=user,
        times_viewed=0,
        last_viewed=datetime.now(),
        date_added=datetime.now(),
        )

    if existing:
      template_args = {
        'existing' : existing,
        'entry' : entry,
        'combined' : '%s, %s' % (existing.definition, entry.definition),
      }
      path = os.path.join(os.path.dirname(__file__), 'conflict.tpl')
      self.response.out.write(template.render(path, template_args))
    else:
      entry.put()
      self.redirect('/entry_mode?lookup=' + urllib.quote(entry_word.encode('utf-8')))


class ConflictResolution(webapp.RequestHandler):
  def post(self):
    entry_word = self.request.get('entry')
    existing = models.CardEntry.all().filter('entry', entry_word).get()
    assert existing

    existing.definition = self.request.get('definition').strip()
    existing.times_viewed = 0
    existing.last_viewed = datetime.now()
    existing.date_added = datetime.now()
    existing.put()
    self.redirect('/entry_mode?lookup=' + urllib.quote(entry_word.encode('utf-8')))
    

application = webapp.WSGIApplication([
    ('/', LandingPage),
    ('/daily_review', DailyReview),
    ('/entry_mode', EntryMode),
    ('/conflict_resolution', ConflictResolution),
    ], debug=True)


if __name__ == '__main__':
  run_wsgi_app(application)
